package com.javaAdmin.exection;

import cn.hutool.core.collection.CollUtil;
import com.javaAdmin.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.xml.bind.ValidationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
/*@ControllerAdvice
@ResponseBody*/
public class SystemExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(SystemExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public Result handlerException(BusinessException e) {
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result exception(Exception e) {
        logger.error("系统异常", e);
        return Result.fail("系统异常");
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException methodArgumentNotValidException) {
        logger.error(methodArgumentNotValidException.getMessage(), methodArgumentNotValidException);
        //validate异常验证 拿到所有的参数校验失败的提示
        List<String> errorMessage = methodArgumentNotValidException.getBindingResult()
                .getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());

        if (CollUtil.isNotEmpty(errorMessage)) {
            String errorMsg = errorMessage.get(0);
            return Result.fail(errorMsg);
        }
        return Result.fail("系统异常");
    }
}
